<!-- eslint-disable vue/multi-word-component-names -->
<template>
    <a-space direction="vertical">
      <a-card title="交易日志信息管理">
        <a-form ref="searchRef" name="searchBar" :model="searchFormState" :labelCol="{ span: 5, offset: 1 }" @finish="handleSearch">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item name="transSerial" label="交易流水">
                <a-input v-model:value="searchFormState.transSerial" ></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="transChannelCode" label="交易渠道">
                <a-select
                  v-model:value="searchFormState.transChannelCode"
                  :loading="transChannelCodeLoading"
                  allowClear        
                >
                  <!-- 遍历字典列表生成选项 -->
                  <a-select-option 
                    v-for="dictDate in transChannelCodeList" 
                    :key="dictDate.dictType" 
                    :value="dictDate.dictValue"
                  >
                    {{ dictDate.dictLabel }}
                  </a-select-option>
                </a-select>                
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24" style="text-align: right">
              <a-button type="primary" html-type="submit" :loading="searchLoading" >搜索</a-button>
              <a-button style="margin: 0 8px" @click="() => searchRef?.resetFields()" >重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <a-card title="查询结果">
        <a-table class="ant-table-striped"
          :rowClassName="
            (_record: any, index: number) => (index % 2 === 1 ? 'table-striped' : null)
          "
          :columns="columns"
          :data-source="data"
          rowKey="id"
          :loading="searchLoading"
          @change="
            (pagination: any) => {
              handleSearch(pagination);
            }
          "
          :pagination="{
            position: [`bottomRight`],
            showSizeChanger: true,
            showQuickJumper: true,
            current: pageNum,
            pageSize,
            total: total,
            showTotal: (total: any) => `总计 ${total} 条记录`,
          }">

          <!-- 操作列插槽：直接使用组件内的handleViewDetail -->
          <template #bodyCell="{ column , record}">
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="handleViewDetail(record)">
                查看详情
              </a-button>
            </template>
          </template>
        </a-table>

        <!-- 新增详情弹窗（参考报文模板详情的布局） -->
        <a-modal
          v-model:visible="detailVisible"
          title="详情信息"
          :maskClosable="false"
          @cancel="handleDetailCancel"
          :footer="null"
          :width="1200"
          :destroyOnClose="true"
        >
          <!-- 页签：默认选中请求报文，只保留功能标签 -->
          <a-tabs 
            v-model:active-key="activeTabKey" 
            style="margin-top: 16px;"
            size="large"
          >
            <!-- 请求报文页签 -->
            <a-tab-pane key="request" tab="请求报文">
              <div class="message-content">
                <!-- 使用文本框（textarea）展示报文内容，支持编辑和滚动 -->
                <a-textarea
                  v-model:value="formattedRequestMsg"
                  :rows="20"  
                  readonly  
                  placeholder="无请求报文数据"
                  style="font-family: SFMono-Regular, Consolas, monospace; font-size: 14px;"
                />
              </div>
            </a-tab-pane>

            <!-- 返回报文页签 -->
            <a-tab-pane key="response" tab="返回报文">
              <div class="message-content">
                <a-textarea
                  v-model:value="formattedResponseMsg"
                  :rows="20"
                  readonly
                  placeholder="无返回报文数据"
                  style="font-family: SFMono-Regular, Consolas, monospace; font-size: 14px;"
                />
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-modal>       
      </a-card>
    </a-space>
  </template>
  <script lang="ts" setup>
  // base library
  import { LISTHEADER } from "./config"; // 从同级config.ts文件中导入表头
  import { listQuery } from "@/api/bmManagement/bmTransLogRecord/bmTransLogRecord";
  import { fetchDictData, DictItem, convertDictValue } from "@/utils/utils"; // 导入公共方法和接口
  import { getInfoByTransLogRecordId } from '@/api/bmManagement/bmTransLogMsg/bmTransLogMsg'; // 第三个文件的接口
  import { onMounted } from "@vue/runtime-core";
  import {
    computed,
    createVNode,
    reactive,
    ref,
    toRaw,
    unref
  } from "vue";
  import { FormInstance, message, Modal } from "ant-design-vue";

  const searchRef = ref<FormInstance>();
  let searchLoading = ref(true);
  const searchFormState: { [propName: string]: any } = reactive({});
  
  const columns = LISTHEADER;
  let pageNum = ref(1);
  let pageSize = ref(10);
  let total = ref(0);
  let data = ref([]);

  const transChannelCodeList = ref<DictItem[]>([]);
  const transChannelCodeLoading = ref(false);

  const handleSearch = (values?: any) => {
    searchLoading.value = true;
    console.log("Received values of form: ", values);
    console.log("searchFormState: ", searchFormState);

    // 1. 复制表单数据并清洗：空字符串转为null
    const cleanForm = { ...searchFormState };
    Object.keys(cleanForm).forEach(key => {
      if (cleanForm[key] === "") { // 仅处理空字符串
        cleanForm[key] = null;
      }
    });

    // 2. 处理分页参数
    let parameter = cleanForm; // 使用清洗后的表单数据
    if (values?.current) {
      pageNum.value = values?.current;
      pageSize.value = values?.pageSize;
    } else {
      pageNum.value = 1;
    }

    // 3. 组装最终请求参数
    const requestParameters = Object.assign({}, parameter, {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
    });
    console.log("清洗后的请求参数:", requestParameters);
  
    // 列表查询及条件查询
    listQuery(requestParameters).then(
      (res: {
        code: number | string;
        msg: string;
        total: number;
        rows: any;
      }) => {
        console.log("打印完整的返回信息：" + res);
        searchLoading.value = false;
        const { code, msg, total: count, rows } = res;
        console.log("接口编码：" + code);
        console.log("接口信息：" + JSON.stringify(rows, null, 2))
        if (code === 200) {
          data.value = rows;
          total.value = count;
        } else {
          total.value = 0;
          data.value = [];
          pageNum.value = 1;
          message.error(msg);
        }
      }
    );
  };
  
  type T = any
  // 查询出的数据表单展示后，选择数据，对选中的数据进行赋值
  const selectedRowKeys = ref<string[]>([]); // 一般存放选中数据的id，由rowKey控制，rowKey取啥字段就存啥字段的值
  const selectedRows = ref<T[]>([]); // 存放选中行的所有数据
  const onSelectChange = (changableRowKeys: string[], changableRows: T[]) => {
    console.log("选中的行ID:", selectedRowKeys);
    console.log("选中的行数据:", selectedRows);
    console.log("selectedRowKeys changed: ", changableRowKeys);
    selectedRowKeys.value = changableRowKeys;
    selectedRows.value = changableRows;
  };

  // 详情弹窗状态
  const detailVisible = ref(false);

  // 在原有脚本中添加以下响应式变量，用于存储格式化后的报文（避免直接修改原始数据）
  const formattedRequestMsg = ref('');
  const formattedResponseMsg = ref('');
  const activeTabKey = ref('request'); // 响应式变量，控制激活的页签

  // 修改 handleViewDetail 方法，赋值格式化后的报文
  const handleViewDetail = (rowData: any) => {
    getInfoByTransLogRecordId(rowData.id).then(
      (res: {
        code: number | string;
        msg: string;
        data: any;
      }) => {
        if (res.code === 200) {
          // 格式化请求/返回报文并赋值给文本框
          formattedRequestMsg.value = formatJson(res.data.requestMsg) || '无请求数据';
          formattedResponseMsg.value = formatJson(res.data.responseMsg) || '无返回数据';
          // 2. 强制切换到请求报文页签（核心：每次打开前重置）
          activeTabKey.value = 'request';
          detailVisible.value = true;
        } else {
          message.error('获取详情失败：' + res.msg);
        }
      }
    );
  };

  // 关闭详情弹窗
  const handleDetailCancel = () => {
    detailVisible.value = false;
  };

  // JSON格式化（参考模板的格式化逻辑）
  const formatJson = (str: string) => {
    try {
      return JSON.stringify(JSON.parse(str), null, 2);
    } catch (e) {
      return str; // 非JSON格式直接展示
    }
  };

  onMounted(() => {
    searchLoading.value = false;
    fetchDictData("trans_channel_code", transChannelCodeList, transChannelCodeLoading);
    //   handleSearch();
  });
  </script>
  
  <style type="less" scoped>
  /* .ant-form-item-label > label {
    width:150px!important;
    justify-content: end!important;
  } */
  .ant-table-striped :deep(.table-striped) td {
    background-color: #fafafa;
  }
  /* 报文文本框容器样式 */
  .message-content {
    padding: 16px;
    background-color: #fafafa;
    border-radius: 4px;
  }
  </style>
  